import React, { useEffect, useState, useCallback } from 'react';
import { Form, Input, Button, Card, Checkbox, Row, Col, Pagination, Tag } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import type { Isetmeal } from '../types/setmeal';
import http from '../api/http';
import { imgBaseURL } from '../api/baseURL';
import '../Subscribe/index.css';

interface PaginationParams {
  current: number; // 当前页码
  pageSize: number; // 每页条数
  total: number; // 总条数
}

interface Props {
  uu: (value: number) => void;
  bb: (value: any) => void;
}

const Subscribe: React.FC<Props> = ({ uu, bb }) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState<PaginationParams>({
    current: 1,
    pageSize: 8, // 卡片缩小后每页可显示更多
    total: 0,
  });

  const [data, setData] = useState<Array<Isetmeal>>([]);
  const [name, setName] = useState('');
  const [zj, setZj] = useState('');

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setName(e.target.value);
  };

  const caidChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setZj(e.target.value);
  };

  const search = useCallback(() => {
    http.getList<Isetmeal>("Setmeal", {
      name: name,
      zj: zj,
      page: pagination.current,
      size: pagination.pageSize
    }).then(res => {
      setData(res.data.filter(n=>n.status==1));
      setPagination(prev => ({
        ...prev,
        total: res.count,
        current: res.page || prev.current,
      }));
    });
  }, [name, zj, pagination.current, pagination.pageSize]);

  useEffect(() => {
    search();
  }, [search]);

  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagination({
      ...pagination,
      current: page,
      pageSize,
    });
  };

  const onSelectChange = (id: React.Key, checked: boolean) => {
    let newSelectedRowKeys;
    if (checked) {
      newSelectedRowKeys = [...selectedRowKeys, id];
    } else {
      newSelectedRowKeys = selectedRowKeys.filter(key => key !== id);
    }
    setSelectedRowKeys(newSelectedRowKeys);
    uu(newSelectedRowKeys.length);
    bb(newSelectedRowKeys);
  };

  // 全选功能
  const handleSelectAll = (checked: boolean) => {
    let newSelectedRowKeys;
    if (checked) {
      newSelectedRowKeys = data.map(item => item.id);
    } else {
      newSelectedRowKeys = [];
    }
    setSelectedRowKeys(newSelectedRowKeys);
    uu(newSelectedRowKeys.length);
    bb(newSelectedRowKeys);
  };

  // 状态标签仅作为展示
  const getStatusTag = (status: number) => {
    return (
      <Tag color={status === 1 ? "green" : "red"} size="small">
        {status === 1 ? "已开启" : "已关闭"}
      </Tag>
    );
  };

  return (
    <div className="subscribe-container" style={{ padding: '16px' }}>
      {/* 搜索区域 */}
      <div style={{ maxWidth: 800, margin: '0 auto 16px', padding: '0 12px' }}>
        <div className="custom-form" style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap' }}>
          <div className="form-item" style={{ margin: 0 }}>
            <Input
              placeholder="请输入套餐名称"
              style={{ width: '180px' }}
              onChange={handleInputChange}
              size="small"
            />
          </div>
          <div className="form-item" style={{ margin: 0, marginLeft: '12px' }}>
            <Input
              placeholder="请输入助记名"
              style={{ width: '180px' }}
              onChange={caidChange}
              size="small"
            />
          </div>
          <Button 
            type="primary" 
            icon={<SearchOutlined />} 
            style={{ marginLeft: '12px' }}
            onClick={search}
            size="small"
          >
            搜索
          </Button>
          
          {/* 全选复选框 */}
          <Checkbox 
            checked={selectedRowKeys.length === data.length && data.length > 0}
            indeterminate={selectedRowKeys.length > 0 && selectedRowKeys.length < data.length}
            onChange={(e) => handleSelectAll(e.target.checked)}
            style={{ marginLeft: 'auto' }}
            size="small"
          >
            全选
          </Checkbox>
        </div>
      </div>

      {/* 卡片列表区域 */}
      <Row gutter={[12, 16]}>
        {data.length > 0 ? (
          data.map((item) => (
            <Col xs={24} sm={12} md={8} lg={6} xl={4} key={item.id}>
              <Card 
                hoverable
                cover={
                  <div style={{ position: 'relative' }}>
                    <img 
                      alt={item.name} 
                      src={imgBaseURL + item.img} 
                      style={{ width: '100%', height: '100px', objectFit: 'cover' }} // 缩小图片高度
                    />
                    <Checkbox
                      checked={selectedRowKeys.includes(item.id)}
                      onChange={(e) => onSelectChange(item.id, e.target.checked)}
                      style={{ 
                        position: 'absolute', 
                        top: '6px', 
                        right: '6px',
                        backgroundColor: 'white',
                        borderRadius: '3px',
                        boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
                      }}
                      size="small"
                    />
                  </div>
                }
                bodyStyle={{ padding: '12px', fontSize: '12px' }} // 减小内边距和字体
              >
                <div>
                  <h3 style={{ margin: '0 0 6px 0', fontSize: '14px', fontWeight: 500 }}>
                    {item.name}
                  </h3>
                  <div style={{ color: '#666', marginBottom: '2px' }}>
                    编号: {item.code}
                  </div>
                  <div style={{ color: '#666', marginBottom: '2px' }}>
                    助记名: {item.helpCode}
                  </div>
                  <div style={{ color: '#666', marginBottom: '2px' }}>
                    适用性别: {item.sex}
                  </div>
                  <div style={{ color: '#666', marginBottom: '4px' }}>
                    年龄: {item.minage}-{item.maxage}岁
                  </div>
                  <div style={{ fontSize: '13px', color: '#f50', margin: '4px 0' }}>
                    ￥{item.price}
                  </div>
                  <div style={{ margin: '6px 0', display: 'flex', alignItems: 'center' }}>
                    <span style={{ color: '#666', marginRight: '6px' }}>状态:</span>
                    {getStatusTag(item.status)}
                  </div>
                  {item.attention && (
                    <div style={{ 
                      color: '#666', 
                      marginTop: '6px',
                      paddingTop: '6px',
                      borderTop: '1px dashed #eee',
                      fontSize: '11px',
                      lineHeight: 1.4
                    }}>
                      <div style={{ marginBottom: '2px', fontWeight: 500 }}>注意:</div>
                      <div>{item.attention}</div>
                    </div>
                  )}
                </div>
              </Card>
            </Col>
          ))
        ) : (
          <Col span={24} style={{ textAlign: 'center', padding: '30px 0' }}>
            <div style={{ color: '#999' }}>暂无数据</div>
          </Col>
        )}
      </Row>

      {/* 分页区域 */}
      {pagination.total > 0 && (
        <div style={{ textAlign: 'center', marginTop: '20px' }}>
          <Pagination
            current={pagination.current}
            pageSize={pagination.pageSize}
            total={pagination.total}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条数据`}
            pageSizeOptions={['8', '16', '24']}
            onChange={handlePaginationChange}
            onShowSizeChange={(current, size) => handlePaginationChange(current, size)}
            size="small"
          />
        </div>
      )}
    </div>
  );
};

export { Subscribe };